<?php

/**
 * @see http://blog.ekini.net/2010/03/05/zend-framework-how-to-use-nested-transactions-with-zend_db-and-mysql/ 
 */
class ZFKiller_Db_Adapter_Pdo_Mysql extends Zend_Db_Adapter_Pdo_Mysql {

    /**
     * Current Transaction Level
     *
     * @var int
     */
    protected $_transactionLevel = 0;

    protected function _connect() {
        try {
            parent::_connect();
        } catch (Exception $exc) {
            die("Sem conexão no momento: " . $this->_config['host']);
        }
    }

    /**
     * Begin new DB transaction for connection
     *
     * @return ZFKiller_Db_Adapter_Pdo_Mysql
     */
    public function beginTransaction() {
        if ($this->_transactionLevel === 0) {
            parent::beginTransaction();
        }
        $this->_transactionLevel++;

        return $this;
    }

    /**
     * Commit DB transaction
     *
     * @return ZFKiller_Db_Adapter_Pdo_Mysql
     */
    public function commit() {
        if ($this->_transactionLevel === 1) {
            parent::commit();
        }
        $this->_transactionLevel--;

        return $this;
    }

    /**
     * Rollback DB transaction
     *
     * @return ZFKiller_Db_Adapter_Pdo_Mysql
     */
    public function rollback() {
        if ($this->_transactionLevel === 1) {
            parent::rollback();
        }
        $this->_transactionLevel--;

        return $this;
    }

    /**
     * Get adapter transaction level state. Return 0 if all transactions are complete
     *
     * @return int
     */
    public function getTransactionLevel() {
        return $this->_transactionLevel;
    }

}